#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
系统设置页面模块
"""

import logging
import os
from PyQt6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
    QTabWidget, QFrame, QGridLayout, QLineEdit, QComboBox,
    QCheckBox, QSpinBox, QFileDialog, QMessageBox, QListWidget,
    QListWidgetItem, QTableWidget, QTableWidgetItem, QHeaderView,
    QFormLayout, QGroupBox, QDialogButtonBox
)
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QIcon, QColor

from app.core.config import save_config


class SettingsPage(QWidget):
    """系统设置页面"""
    
    def __init__(self, config, database=None, task_scheduler=None):
        super().__init__()
        self.config = config
        self.database = database
        self.task_scheduler = task_scheduler
        self._setup_ui()
        self._load_settings()
        logging.info("系统设置页面已初始化")
    
    def _setup_ui(self):
        """设置UI"""
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(20, 20, 20, 20)
        
        # 标题
        title_label = QLabel("系统设置")
        title_label.setStyleSheet("font-size: 24px; font-weight: bold;")
        main_layout.addWidget(title_label)
        
        # 设置标签页
        self.tabs = QTabWidget()
        
        # 基本设置标签页
        self.basic_tab = QWidget()
        self._setup_basic_tab()
        self.tabs.addTab(self.basic_tab, "基本设置")
        
        # 数据库设置标签页
        self.database_tab = QWidget()
        self._setup_database_tab()
        self.tabs.addTab(self.database_tab, "数据库设置")
        
        # 集群设置标签页
        self.cluster_tab = QWidget()
        self._setup_cluster_tab()
        self.tabs.addTab(self.cluster_tab, "集群设置")
        
        # 触发器设置标签页
        self.triggers_tab = QWidget()
        self._setup_triggers_tab()
        self.tabs.addTab(self.triggers_tab, "触发器设置")
        
        main_layout.addWidget(self.tabs)
        
        # 按钮区域
        buttons_layout = QHBoxLayout()
        buttons_layout.addStretch()
        
        # 保存按钮
        self.save_btn = QPushButton("保存设置")
        self.save_btn.clicked.connect(self._save_settings)
        buttons_layout.addWidget(self.save_btn)
        
        # 重置按钮
        self.reset_btn = QPushButton("重置设置")
        self.reset_btn.clicked.connect(self._reset_settings)
        buttons_layout.addWidget(self.reset_btn)
        
        main_layout.addLayout(buttons_layout)
    
    def _setup_basic_tab(self):
        """设置基本设置标签页"""
        layout = QVBoxLayout(self.basic_tab)
        
        # 应用设置组
        app_group = QGroupBox("应用设置")
        app_layout = QFormLayout(app_group)
        
        # 应用名称
        self.app_name_edit = QLineEdit()
        app_layout.addRow("应用名称:", self.app_name_edit)
        
        # 数据目录
        data_dir_layout = QHBoxLayout()
        self.data_dir_edit = QLineEdit()
        self.data_dir_edit.setReadOnly(True)
        data_dir_layout.addWidget(self.data_dir_edit)
        
        browse_data_btn = QPushButton("浏览...")
        browse_data_btn.clicked.connect(lambda: self._browse_directory(self.data_dir_edit))
        data_dir_layout.addWidget(browse_data_btn)
        
        app_layout.addRow("数据目录:", data_dir_layout)
        
        # 日志目录
        log_dir_layout = QHBoxLayout()
        self.log_dir_edit = QLineEdit()
        self.log_dir_edit.setReadOnly(True)
        log_dir_layout.addWidget(self.log_dir_edit)
        
        browse_log_btn = QPushButton("浏览...")
        browse_log_btn.clicked.connect(lambda: self._browse_directory(self.log_dir_edit))
        log_dir_layout.addWidget(browse_log_btn)
        
        app_layout.addRow("日志目录:", log_dir_layout)
        
        layout.addWidget(app_group)
        
        # 界面设置组
        ui_group = QGroupBox("界面设置")
        ui_layout = QFormLayout(ui_group)
        
        # 自动刷新间隔
        self.refresh_interval_spinbox = QSpinBox()
        self.refresh_interval_spinbox.setRange(1, 60)
        self.refresh_interval_spinbox.setSuffix(" 秒")
        ui_layout.addRow("自动刷新间隔:", self.refresh_interval_spinbox)
        
        # 显示状态栏
        self.show_statusbar_checkbox = QCheckBox()
        ui_layout.addRow("显示状态栏:", self.show_statusbar_checkbox)
        
        layout.addWidget(ui_group)
        
        # 添加弹性空间
        layout.addStretch()
    
    def _setup_database_tab(self):
        """设置数据库设置标签页"""
        layout = QVBoxLayout(self.database_tab)
        
        # 数据库设置组
        db_group = QGroupBox("数据库设置")
        db_layout = QFormLayout(db_group)
        
        # 数据库类型
        self.db_type_combo = QComboBox()
        self.db_type_combo.addItems(["sqlite", "mysql", "postgresql"])
        db_layout.addRow("数据库类型:", self.db_type_combo)
        
        # 数据库路径/连接字符串
        db_path_layout = QHBoxLayout()
        self.db_path_edit = QLineEdit()
        db_path_layout.addWidget(self.db_path_edit)
        
        browse_db_btn = QPushButton("浏览...")
        browse_db_btn.clicked.connect(lambda: self._browse_file(self.db_path_edit, "数据库文件 (*.db *.sqlite)"))
        db_path_layout.addWidget(browse_db_btn)
        
        db_layout.addRow("数据库路径:", db_path_layout)
        
        layout.addWidget(db_group)
        
        # 添加弹性空间
        layout.addStretch()
    
    def _setup_cluster_tab(self):
        """设置集群设置标签页"""
        layout = QVBoxLayout(self.cluster_tab)
        
        # 集群设置组
        cluster_group = QGroupBox("集群设置")
        cluster_layout = QFormLayout(cluster_group)
        
        # 集群模式
        self.cluster_mode_combo = QComboBox()
        self.cluster_mode_combo.addItems(["单机模式", "主从模式", "集群模式"])
        cluster_layout.addRow("集群模式:", self.cluster_mode_combo)
        
        # 节点ID
        self.node_id_edit = QLineEdit()
        cluster_layout.addRow("节点ID:", self.node_id_edit)
        
        # 主节点地址
        self.master_address_edit = QLineEdit()
        cluster_layout.addRow("主节点地址:", self.master_address_edit)
        
        # 节点角色
        self.node_role_combo = QComboBox()
        self.node_role_combo.addItems(["主节点", "从节点"])
        cluster_layout.addRow("节点角色:", self.node_role_combo)
        
        # 心跳间隔
        self.heartbeat_interval_spinbox = QSpinBox()
        self.heartbeat_interval_spinbox.setRange(1, 60)
        self.heartbeat_interval_spinbox.setSuffix(" 秒")
        cluster_layout.addRow("心跳间隔:", self.heartbeat_interval_spinbox)
        
        layout.addWidget(cluster_group)
        
        # 添加弹性空间
        layout.addStretch()
    
    def _setup_triggers_tab(self):
        """设置触发器设置标签页"""
        layout = QVBoxLayout(self.triggers_tab)
        
        # 触发器设置组
        triggers_group = QGroupBox("触发器设置")
        triggers_layout = QFormLayout(triggers_group)
        
        # 触发器类型
        self.trigger_type_combo = QComboBox()
        self.trigger_type_combo.addItems(["数据触发器", "业务触发器"])
        triggers_layout.addRow("触发器类型:", self.trigger_type_combo)
        
        # 触发器名称
        self.trigger_name_edit = QLineEdit()
        triggers_layout.addRow("触发器名称:", self.trigger_name_edit)
        
        # 触发器表达式
        self.trigger_expression_edit = QLineEdit()
        triggers_layout.addRow("触发器表达式:", self.trigger_expression_edit)
        
        layout.addWidget(triggers_group)
        
        # 添加弹性空间
        layout.addStretch()
    
    def _save_settings(self):
        """保存设置"""
        try:
            # 基本设置
            self.config["app_name"] = self.app_name_edit.text()
            self.config["data_dir"] = self.data_dir_edit.text()
            self.config["log_dir"] = self.log_dir_edit.text()
            self.config["refresh_interval"] = self.refresh_interval_spinbox.value()
            self.config["show_statusbar"] = self.show_statusbar_checkbox.isChecked()
            
            # 数据库设置
            if "database" not in self.config:
                self.config["database"] = {}
            self.config["database"]["type"] = self.db_type_combo.currentText()
            self.config["database"]["path"] = self.db_path_edit.text()
            
            # 集群设置
            if "cluster" not in self.config:
                self.config["cluster"] = {}
            self.config["cluster"]["mode"] = self.cluster_mode_combo.currentText()
            self.config["cluster"]["node_id"] = self.node_id_edit.text()
            self.config["cluster"]["master_address"] = self.master_address_edit.text()
            self.config["cluster"]["node_role"] = self.node_role_combo.currentText()
            self.config["cluster"]["heartbeat_interval"] = self.heartbeat_interval_spinbox.value()
            
            # 触发器设置
            if "trigger" not in self.config:
                self.config["trigger"] = {}
            self.config["trigger"]["type"] = self.trigger_type_combo.currentText()
            self.config["trigger"]["name"] = self.trigger_name_edit.text()
            self.config["trigger"]["expression"] = self.trigger_expression_edit.text()
            
            # 保存到文件
            save_config(self.config)
            
            logging.info("设置已保存")
            QMessageBox.information(self, "成功", "设置已保存")
        except Exception as e:
            logging.error(f"保存设置失败: {str(e)}")
            QMessageBox.warning(self, "错误", f"保存设置失败: {str(e)}")
    
    def _load_settings(self):
        """加载设置"""
        try:
            # 基本设置
            self.app_name_edit.setText(self.config.get("app_name", ""))
            self.data_dir_edit.setText(self.config.get("data_dir", ""))
            self.log_dir_edit.setText(self.config.get("log_dir", ""))
            self.refresh_interval_spinbox.setValue(self.config.get("refresh_interval", 5))
            self.show_statusbar_checkbox.setChecked(self.config.get("show_statusbar", True))
            
            # 数据库设置
            self.db_type_combo.setCurrentText(self.config.get("database", {}).get("type", "sqlite"))
            self.db_path_edit.setText(self.config.get("database", {}).get("path", ""))
            
            # 集群设置
            self.cluster_mode_combo.setCurrentText(self.config.get("cluster", {}).get("mode", "单机模式"))
            self.node_id_edit.setText(self.config.get("cluster", {}).get("node_id", ""))
            self.master_address_edit.setText(self.config.get("cluster", {}).get("master_address", ""))
            self.node_role_combo.setCurrentText(self.config.get("cluster", {}).get("node_role", "主节点"))
            self.heartbeat_interval_spinbox.setValue(self.config.get("cluster", {}).get("heartbeat_interval", 5))
            
            # 触发器设置
            self.trigger_type_combo.setCurrentText(self.config.get("trigger", {}).get("type", "数据触发器"))
            self.trigger_name_edit.setText(self.config.get("trigger", {}).get("name", ""))
            self.trigger_expression_edit.setText(self.config.get("trigger", {}).get("expression", ""))
            
            logging.info("设置已加载")
        except Exception as e:
            logging.error(f"加载设置失败: {str(e)}")
            QMessageBox.warning(self, "错误", f"加载设置失败: {str(e)}")
    
    def _reset_settings(self):
        """重置设置"""
        try:
            reply = QMessageBox.question(
                self, "确认", "确定要重置所有设置吗？",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
            )
            
            if reply == QMessageBox.StandardButton.Yes:
                # 重置为默认值
                self.app_name_edit.clear()
                self.data_dir_edit.clear()
                self.log_dir_edit.clear()
                self.refresh_interval_spinbox.setValue(5)
                self.show_statusbar_checkbox.setChecked(True)
                
                self.db_type_combo.setCurrentText("sqlite")
                self.db_path_edit.clear()
                
                self.cluster_mode_combo.setCurrentText("单机模式")
                self.node_id_edit.clear()
                self.master_address_edit.clear()
                self.node_role_combo.setCurrentText("主节点")
                self.heartbeat_interval_spinbox.setValue(5)
                
                self.trigger_type_combo.setCurrentText("数据触发器")
                self.trigger_name_edit.clear()
                self.trigger_expression_edit.clear()
                
                logging.info("设置已重置")
                QMessageBox.information(self, "成功", "设置已重置")
        except Exception as e:
            logging.error(f"重置设置失败: {str(e)}")
            QMessageBox.warning(self, "错误", f"重置设置失败: {str(e)}")
    
    def _browse_directory(self, line_edit):
        """浏览目录"""
        directory = QFileDialog.getExistingDirectory(
            self, "选择目录", line_edit.text()
        )
        if directory:
            line_edit.setText(directory)
    
    def _browse_file(self, line_edit, filter_str):
        """浏览文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择文件", line_edit.text(), filter_str
        )
        if file_path:
            line_edit.setText(file_path)